import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import _ from 'lodash'

import { Table, Icon, Tag, message, Modal, Popover, Button,Alert,Badge } from 'antd';
import {fetchArgs,FetchURL,fetchData,removeData,createData,updateData,changePage,getAccount} from '../../store/actions';
import FormSpecialistProduct from '../../components/form-specialist-product'

class _SpecialistProduct extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            visible:false,
            id:null,
            user: this.props.user,
            title:'',
            modalInitial:'',
            confirmLoading: false,
            SpecialistProductLen:0,
            FromType: 0,//0:自身 1：专家工作台 2：管理员后台
            SpecialistId: '',//专家id
            NewSproductNum: 0//新专家产品数量
        };
        this._changePage = this._changePage.bind(this);
        this.fetchSpecialistProduct=this.fetchSpecialistProduct.bind(this);
        this.newSpecialistImport = this.newSpecialistImport.bind(this);
        this.onSelectChange = this.onSelectChange.bind(this);
        this.reFetch = this.reFetch.bind(this);
        this.Edit = this.Edit.bind(this);
        this.delData = this.delData.bind(this);
        this.switch = this.switch.bind(this);
    };
    fetchSpecialistProduct(){
        const _this = this;
        //formType来源
        let _formType = 0;//0:自身 1：专家工作台 2：管理员后台
        if(_this.props.FromType && _this.props.FromType=='specialist')
            _formType = 1;
        else if(_this.props.FromType && _this.props.FromType=='admin')
            _formType = 2;
        //specialistId专家id
        let _SpecialistId = '';
        const _user = getAccount();
        if(_user){
            _SpecialistId =_user.user.specialist_id;
        }
        _SpecialistId = _this.props.SpecialistId || _SpecialistId;
        _this.setState({
            FormType: _formType,
            SpecialistId:  _SpecialistId
        });
        //获取专家产品数据
        let _args = Object.assign({},fetchArgs);
        _args.Id = _SpecialistId;
        _args.URL = FetchURL.SPECIALIST_PRODUCT;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            _this.setState({
                data: res.content.list,
                SpecialistProductLen: res.content.list.length
            });
            //判断是否有产品发布
            (()=>{
                let _args = Object.assign({},fetchArgs);
                _args.Id = _SpecialistId;
                _args.URL = FetchURL.NEWSPRODUCT;
                _args.IsAuth = true;
                _args.IsShowErrorMsg = false;
                _args.Succ = function (res) {
                    _this.setState({
                        NewSproductNum: res.content.list.length
                    });
                };
                _this.props.dispatch(fetchData(_args));
            })();
        };
        _this.props.dispatch(fetchData(_args));

    };
    //专家导入产品
    newSpecialistImport(){
        const _this = this;
        //specialistId专家id
        let _SpecialistId = '';
        const _user = getAccount();
        if(_user){
            _SpecialistId =_user.user.specialist_id;
        }
        _SpecialistId = _this.props.SpecialistId || _SpecialistId;
        let _args = Object.assign({},fetchArgs);
        _args.Id = _SpecialistId;
        _args.URL = FetchURL.NEWSPRODUCT;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            message.success('产品导入成功');
            _this.reFetch();
            _this.setState({
                NewSproductNum: 0
            });
        };
        _this.props.dispatch(createData(_args));
    };
    componentWillMount(){
        this.fetchSpecialistProduct();
    };
    static contextType = {
        router:React.PropTypes.object
    };
    _changePage(){
        // this.props.dispatch(changePge(''));
    };
    onSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys });
    };
    reFetch(){
        this.setState({
            visible:false,
            id:null,
            targetData:null
        });
        this.fetchSpecialistProduct();
    };
    delData(e){
        e.preventDefault();
        const _t = e.target.dataset;
        this.setState({id:_t.id});
        const modalOpts = {
            title:'删除数据项',
            content: `要删除 ${_t.name} 吗？`,
            okText: ` 删除 `,
            onOk:this.delOk.bind(this)
        };
        Modal.confirm({...modalOpts})
    };
    delOk(){
        const _this = this;
        let _args = Object.assign({},fetchArgs);
        _args.Id = this.state.id;
        _args.URL = FetchURL.SPECIALIST_PRODUCT;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            message.success('删除专家专家产品成功', 1, function () {
                _this.reFetch();
                _this.setState({
                    visible:false,
                    id:null,
                    title:'',
                    modalInitial:'',
                    confirmLoading: false
                });
            });
        };
        _this.props.dispatch(removeData(_args));
    };
    addData(e){
        e.preventDefault();
        this.setState({
            visible:true,
            id:null,
            title:'新建',
            targetData:null
        });
    };
    Edit(e){
        e.preventDefault();
        const _t = e.target.dataset;
        const targetData = _.filter(this.state.data,{id: _t.id})[0];
        this.setState({
            user: this.props.user,
            id : _t.id,
            visible:true,
            title:'编辑',
            targetData:targetData
        });
    };
    onCancel(){
        this.setState({
            visible:false
        });
    };
    switch(e){
        e.preventDefault();
        const _t = e.target.dataset,
            _this = this,
            id = e.target.id,
            target = _.filter(_this.state.data,_o => {
                return _o.id == id
            })[0];
        function switchStatus(){
            //specialistId专家id
            let _SpecialistId = '';
            const _user = getAccount();
            if(_user){
                _SpecialistId =_user.user.specialist_id;
            }
            _SpecialistId = _this.props.SpecialistId || _SpecialistId;
            let _args = Object.assign({},fetchArgs);
            _args.Id = _SpecialistId;
            _args.URL = FetchURL.SPRODUCT;
            _args.IsAuth = true;
            _args.SendData = {
                specialist_id: _SpecialistId,
                product_id: target.id
            }
            if(_t.type === 'on'){
                _args.SendData.status = 1;
                _args.Succ = function(){
                    message.success(`产品（${_t.name}）被启用`,2);
                    _this.reFetch();
                }
            }else if(_t.type === 'off'){
                _args.SendData.status = 0;
                _args.Succ =  function(){
                    message.success(`产品（${_t.name}）被停用`,2);
                    _this.reFetch();
                }
            }
            _this.props.dispatch(updateData(_args));
        }
        const modalOpts = {
            title: _t.type == 'on'?'启用产品':'停用产品',
            content: _t.type == 'on'?`确认要启用产品 ${_t.name} 吗？`:`确认要停用产品 ${_t.name} 吗？`,
            okText: _t.type == 'on'?'启用':'停用',
            onOk:switchStatus
        };
        Modal.confirm({...modalOpts})
    }
    render(){
        const _this = this;
        const columns=[{
            title:'编码',
            dataIndex:'code',
            width:100
        },{
            title:'名称',
            dataIndex:'name',
            width:200
        }, {
            title:'类型',
            dataIndex:'type',
            width:100,
            render:(text,record)=>{
                switch (text){
                    case 'R':
                        return <span>报告(R)</span>;
                    case 'G':
                        return <span>图文交流/报告(G)</span>;
                    case 'V':
                        return <span>音视频交流/报告(V)</span>;
                    default:
                        return <span>未知</span>;
                }
            }
        },{
            title:'时长(分钟)',
            dataIndex:'duration',
            width:100
        },{
            title:'价格(元)',
            dataIndex:'price',
            width:100
        }, {
            title:'状态',
            dataIndex:'status',
            width:100,
            className: 'ant-column-status',
            render:(text,record)=>{
                switch (text){
                    case 1:
                    case '1':
                        return <span style={{color:'green'}}>启用</span>;
                    case 0:
                    case '0':
                        return <span style={{color:'red'}}>未启用</span>;
                    default:
                        return <span>未知</span>;
                }
            }
        },{
            title:'描述',
            dataIndex:'description',
            width:200
        },{
            title:'操作',
            width:200,
            className: 'ant-column-operation',
            render:(text,record) => {
                switch(record.status) {
                    case 1:
                        return (<div>
                                    <a href="#" data-type='off' data-name={`${record.name}`} onClick={_this.switch} id={`${record.id}`}>停用</a>
                                    <span className="ant-divider"> </span>
                                    <a href="#" data-id={`${record.id}`} onClick={this.Edit}>编辑</a>
                                </div>);
                    case 0:
                        return (<div>
                                    <a href="#" data-type='on' data-name={`${record.name}`} onClick={_this.switch} id={`${record.id}`}>启用</a>
                                    <span className="ant-divider"> </span>
                                    <a href="#" data-id={`${record.id}`} onClick={this.Edit}>编辑</a>
                                </div>);
                    default:
                        return '--';
                }
            }
        }];
        const dataLen = this.state.SpecialistProductLen;
        const pagination = {
            total:dataLen,
            showSizeChanger:true,
            onShowSizeChange(current,pageSize){
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current){
                /*console.log('Current: ', current);*/
            }
        };
        const rowSelection = {};
        //html 必须加html元素否则报语法错误
        let _html =
         (
            <div>
                <Badge>
                    <Alert message="有新产品发布啦"
                           description={'近期发布了 '+`${this.state.NewSproductNum}`+' 款新的产品，看看是否有适合您的'}
                           type="info"
                           showIcon
                    />
                </Badge>
                 <Badge count={`${this.state.NewSproductNum}`}>
                    <Button className="import" onClick={this.newSpecialistImport}  type="primary">立即导入</Button>
                 </Badge>
            </div>
        );
        return(
            <div id="specialistProduct">
                {this.state.NewSproductNum>0 ? _html : ''}
                <Table bordered rowSelection={rowSelection} columns={columns} dataSource={this.state.data} pagination={pagination}/>
                <FormSpecialistProduct
                    user={this.state.user}
                    visible = {this.state.visible}
                    title = {this.state.title}
                    confirmLoading = {this.state.confirmLoading}
                    targetData = {this.state.targetData}
                    onCancel = {this.onCancel.bind(this)}
                    dispatch={this.props.dispatch}
                    id={this.state.id}
                    reFetch ={this.reFetch}
                />
            </div>
        )
    };
}
let SpecialistProduct;
export default SpecialistProduct = connect((state) => {
    const {user} = state.rootReducer;
    return {user}
})(_SpecialistProduct);